const db = require('../database/mysql');
const bcrypt = require('bcryptjs');
const config = require('./config');
const jwt = require('jsonwebtoken');

// 引入我们生成的secretKey
const secretKey = config.jwtSecretKey;

// 登录
exports.login = (req, res) => {
    // 符合账号名且没有被删除
    const sqlstr = 'SELECT * FROM sy_users WHERE username = ? AND isdeleted = ?';
    console.log(req.body);
    const userInfo = req.body;
    db.query(sqlstr, [req.body.username, 0], (err, result) => {
        if (err) {
            return res.cc(err);
        } else if (result.length == 1) {     //判断是否找到用户名
            // 判断密码是否正确
            const compareRes = bcrypt.compareSync(userInfo.password,result[0].password);
            if (compareRes) {
                // 用空字符串把密码等敏感信息替换掉
                const user = { ...result[0], password: '' };
                console.log("展开得到的结果是", user);
                console.log("key", secretKey);
                // 根据secretKey来生成token,和解密
                const token = 'Bearer ' + jwt.sign(user, secretKey, { expiresIn: '30min' });
                res.send({
                    status: 200,
                    msg: "登录成功！",
                    token: token,
                })
            } else {
                return res.cc("密码错误", 1);
            }
        } else {
            return res.cc(" 没有找到该用户名，请注册后登录！", 1);
        }
    })
}
// 把用户名和密码插入数据库
exports.registerUser = (req, res) => {
    const info = req.body;
    console.log(info);
    const sqlstr1 = 'SELECT * FROM sy_users  WHERE username = ? AND isdeleted = ?'
    db.query(sqlstr1,[info.username,0],(err,result)=>{
        if (err) {
            return res.cc(err,1);
        }else if(result.length>=1){
            console.log(result)
            return res.cc("注册失败,用户名名已被使用，请换一个试试",1);
        }else{
            const sqlstr = 'INSERT INTO sy_users SET ? ';
            db.query(sqlstr, info, (err, intoResult) => {
                if (intoResult.affectedRows !== 1) {
                    return res.cc(err, 1);
                } else {
                    res.send({
                        status: 200,
                        msg: "注册成功！"
                    })
                }
            });
        }
    });
}